<template>
  <div
   destroyOnClose={true}
   v-if="visible"
   class="modal-overlay"
   @click.self="closeModal"
   >
    <div class="modal-content" @click.stop>
      <h2>设备导入</h2>
      <div class="upload-container">
        <div class="drag-drop-area" @drop="handleDrop" @dragover="handleDragOver" @click="openFileSelector">
          <CloudUploadOutlined style="font-size: 60px; color: #999;" class="cloud-icon" />
          <p>将文件放在此处或单击上载</p>
        </div>
        <input ref="fileInputRef" type="file" accept=".xls,.xlsx" @change="handleFileChange" style="display: none;">
      </div>
      <p>仅允许导入 “xls” 或 “xlsx” 格式文件!</p>
      <a-button style="margin-left:35%;margin-right:30%;" type="primary" @click="handleDownload">下载模板</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, onMounted, defineEmits, watch } from 'vue';
import { CloudUploadOutlined } from '@ant-design/icons-vue';
import { Button as AButton } from 'ant-design-vue';
import { uploadDevice } from '/@/api/device.management/inDeviceManagement'; // 引入上传接口
import { useMessage } from '/@/hooks/web/useMessage'; // 引入消息提示

const { showMessage } = useMessage();

// 定义组件接收的属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

// 定义响应式数据
const visible = ref(props.modelValue);
const selectedFile = ref(null);
const fileInputRef = ref(null);

// 定义组件可以触发的自定义事件
const emits = defineEmits(['upload', 'download', 'update:modelValue']);

// 处理文件拖拽进入区域的事件
const handleDragOver = (e) => {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'copy';
};

// 处理文件拖拽放下的事件
const handleDrop = async (e) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0];
  console.log('Dropped file:', file);
  if (file && (file.name.endsWith('.xls') || file.name.endsWith('.xlsx'))) {
    selectedFile.value = file;
    await uploadSelectedFile();
  }
};

// 处理文件选择框文件改变的事件
const handleFileChange = async (e) => {
  const file = e.target.files[0];
  console.log('Selected file:', file);
  if (file && (file.name.endsWith('.xls') || file.name.endsWith('.xlsx'))) {
    selectedFile.value = file;
    await uploadSelectedFile();
  }
};

// 上传选中的文件
const uploadSelectedFile = async () => {
  if (selectedFile.value) {
    let formData = new FormData();
    formData.append('file', selectedFile.value);
    console.log('Selected File:', selectedFile.value);

    // 遍历 FormData 内容
    for (let pair of formData.entries()) {
      console.log('formData.entries', pair[0] + ': ', pair[1]);
    }

    try {
      // 添加调试信息
      console.log('Before uploadDevice call, formData:', formData);
      // 只传递 FormData 对象
      const res = await uploadDevice(formData);
      console.log('After uploadDevice call, response:', res);
      showMessage(res.message);
      emits('upload', selectedFile.value);
      closeModal();
    } catch (error) {
      showMessage('文件上传过程中出现错误', 'error');
    }
  } else {
    console.log('请选择文件');
  }
};

// 处理下载模板的事件
const handleDownload = () => {
  emits('download');
};

// 处理关闭模态框的事件
const closeModal = () => {
  emits('update:modelValue', false);
};

// 打开文件选择框
const openFileSelector = () => {
  fileInputRef.value.click();
};

// 可以在这里添加一些组件挂载后的逻辑，比如初始化操作
onMounted(() => {
  // 这里可以写具体的初始化代码
});

// 监听 props.modelValue 的变化
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue;
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

.upload-container {
  border: 2px dashed #ccc;
  border-radius: 5px;
  padding: 20px;
  text-align: center;
  margin-bottom: 15px;
  cursor: pointer;
}

.drag-drop-area {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>